<%@page import="fi.foyt.cs.persistence.domainmodel.task.TaskRewardItem"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<%@page import="java.util.Collections"%>
<%@page import="java.util.Comparator"%>
<%@page import="java.util.Arrays"%>
<%@page import="java.util.List"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.TaskRewards"%>
<%@page import="fi.foyt.cs.Settings"%>
<%@page import="fi.foyt.cs.controller.LocaleController"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.locale.LocaleElement"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.items.Item"%>
<%@page import="fi.foyt.cs.controller.ItemController"%>
<%@page import="fi.foyt.cs.controller.TaskController"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.GeneralTask"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.GeneralTaskLevel"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.TaskRequirementItem"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.TaskRequirements"%>
<%@page import="org.apache.commons.lang3.math.NumberUtils"%>
<%@page import="org.apache.commons.lang3.StringUtils"%>

<%
  Long taskId = NumberUtils.createLong(request.getParameter("taskId"));

  TaskController taskController = new TaskController();
  ItemController itemController = new ItemController();
  LocaleController localeController = new LocaleController();
  
  GeneralTask generalTask = taskController.findGeneralTaskById(taskId);
  List<GeneralTaskLevel> generalTaskLevels = taskController.listGeneralTaskLevels(generalTask);
  Collections.sort(generalTaskLevels, new Comparator<GeneralTaskLevel>() {
    public int compare(GeneralTaskLevel o1, GeneralTaskLevel o2) {
      return o1.getLevelNumber().compareTo(o2.getLevelNumber());
    }
  });
  
  if ("POST".equals(request.getMethod())) {
    int levelCount = NumberUtils.createInteger(request.getParameter("levelCount"));
    
    for (int i = 1; i < (levelCount + 1); i++) {
      String taskLevelIdParam = request.getParameter("genericTaskLevelId." + i);
      Long taskLevelId = StringUtils.isBlank(taskLevelIdParam) ? null : NumberUtils.createLong(taskLevelIdParam);
      Double rewardMoney = NumberUtils.createDouble(request.getParameter("rewardMoney." + i));
      Double requirementMoney = NumberUtils.createDouble(request.getParameter("requirementMoney." + i));
      int requirementItemsCount = NumberUtils.createInteger(request.getParameter("requirementItemsCount." + i));
      int rewardItemsCount = NumberUtils.createInteger(request.getParameter("rewardItemsCount." + i));
      
      GeneralTaskLevel generalTaskLevel;
      TaskRequirements taskRequirements;
      TaskRewards taskRewards;
      
      if (taskLevelId != null) {
        generalTaskLevel = taskController.findGeneralTaskLevelById(taskLevelId);
        taskRewards = taskController.findTaskRewardsById(generalTaskLevel.getTaskRewardsId());
        taskRequirements = taskController.findTaskRequirementsById(generalTaskLevel.getTaskRequirementsId());
        taskController.updateTaskRewardsMoney(taskRewards, rewardMoney);
        taskController.updateTaskRequirementsMoney(taskRequirements, requirementMoney);
      } else {
        taskRewards = taskController.createTaskRewards(rewardMoney);
        taskRequirements = taskController.createTaskRequirements(requirementMoney);
        generalTaskLevel = taskController.createGeneralTaskLevel(generalTask, taskRewards, taskRequirements, i);
      }
      
      for (int j = 0; j < requirementItemsCount; j++) {
        String requirementItemIdParam = request.getParameter("requirementItemId." + i + "." + j);
        Long requirementItemId = StringUtils.isBlank(requirementItemIdParam) ? null : NumberUtils.createLong(requirementItemIdParam);
        Long requirementItem = NumberUtils.createLong(request.getParameter("requirementItem." + i + "." + j));
        Integer requirementItemCount = NumberUtils.createInteger(request.getParameter("requirementItemCount." + i + "." + j));
      
        Item item = itemController.findItemById(requirementItem);
        
        if ((requirementItemId == null) && (requirementItemCount.intValue() > 0)) {
          taskController.createTaskRequirementItem(taskRequirements, item, requirementItemCount);          
        } else {
          TaskRequirementItem taskRequirementItem = taskController.findTaskRequirementItemById(requirementItemId);
          
          if (requirementItemCount.intValue() == 0) {
            taskController.deleteTaskRequirementItem(taskRequirementItem);
          } else {
            taskController.updateTaskRequirementItemCount(taskRequirementItem, requirementItemCount);
            taskController.updateTaskRequirementItemItem(taskRequirementItem, item);
          }
        }
      }
      
      for (int j = 0; j < rewardItemsCount; j++) {
        String rewardItemIdParam = request.getParameter("rewardItemId." + i + "." + j);
        Long rewardItemId = StringUtils.isBlank(rewardItemIdParam) ? null : NumberUtils.createLong(rewardItemIdParam);
        Long rewardItem = NumberUtils.createLong(request.getParameter("rewardItem." + i + "." + j));
        Integer rewardItemCount = NumberUtils.createInteger(request.getParameter("rewardItemCount." + i + "." + j));
      
        Item item = itemController.findItemById(rewardItem);
        
        if ((rewardItemId == null) && (rewardItemCount.intValue() > 0)) {
          taskController.createTaskRewardItem(taskRewards, item, rewardItemCount);          
        } else {
          TaskRewardItem taskRewardItem = taskController.findTaskRewardItemById(rewardItemId);
          
          if (rewardItemCount.intValue() == 0) {
            taskController.deleteTaskRewardItem(taskRewardItem);
          } else {
            taskController.updateTaskRewardItemCount(taskRewardItem, rewardItemCount);
            taskController.updateTaskRewardItemItem(taskRewardItem, item);
          }
        }
      }
    }
  } else {
    pageContext.setAttribute("levelCount", generalTaskLevels.size());
  }
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/admin/css/dialog.css" />
    <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/admin/css/scripty2/theme.css" />
    <script type="text/javascript" src="${pageContext.request.contextPath}/script/prototype/prototype.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/script/scripty2/s2.js"></script>
  
		<script type="text/javascript">
		  var ITEMS = new Hash();
		  <%
		    for (Item item : itemController.listAllItems()) {
          LocaleElement localeElement = localeController.findLocaleElementById(item.getLocaleElementId());
          String itemName = localeController.getLocalizedText(localeElement, Settings.getDefaultLocale());
          pageContext.setAttribute("itemName", itemName);
          pageContext.setAttribute("itemId", item.getId().getId());
      %>
          ITEMS.set('${itemId}', '${itemName}');
		  <%
		    }
		  %>
		
		  var NEXT_LEVEL_NUMBER = ${levelCount + 1};
		
			function toggleTaskLevel(event) {
			  var titleElement = Event.element(event);
			  var levelElement = $(titleElement.parentNode);
			  var containerElement = levelElement.down('.genericTaskLevelContainer');
			
			  if (levelElement.hasClassName("genericTaskClosed")) {
			    new S2.FX.SlideUp(containerElement, {
			      after: function () {
			        levelElement.removeClassName('genericTaskClosed');
			        new S2.FX.SlideDown(containerElement, {
			            duration: 0.3
			        }).play();
			      },
			      duration: 0
			    }).play();
			  } else {
			    new S2.FX.SlideUp(containerElement, {
			      after: function () {
			        levelElement.addClassName('genericTaskClosed');
			      },
			      duration: 0.3
			    }).play();
			  }
			}
			
			function addLevel(id, level, rewardMoney, requirementMoney) {
				var genericTaskLevel = new Element("div", {className: "genericTaskLevel", id: "genericTaskLevel_" + level});
				var genericTaskLevelId = new Element("input", {name: "genericTaskLevelId." + level, type: "hidden", value: id});
        var genericTaskLevelRequirementItemsCount = new Element("input", {name: "requirementItemsCount." + level, type: "hidden", value: "0"});
        var genericTaskLevelRewardItemsCount = new Element("input", {name: "rewardItemsCount." + level, type: "hidden", value: "0"});
            
				var genericTaskLevelTitle = new Element("div", {className: "genericTaskLevelTitle", title: "Open / Close", onclick:"toggleTaskLevel(event);"}).update("Level " + level);
				var genericTaskLevelContainer = new Element("div", {className: "genericTaskLevelContainer"});
				var genericTasksRequirementsTitle = new Element("div", {className: "genericTasksRequirementsTitle"}).update('Requirements');
		    var genericTasksRequirementsContainer = new Element("div", {className: "genericTasksRequirementsContainer"});
	      var genericTasksRewardsTitle = new Element("div", {className: "genericTasksRewardsTitle"}).update('Rewards');
        var genericTasksRewardsContainer = new Element("div", {className: "genericTasksRewardsContainer"});
        var genericTasksRequirementsActionsContainer = new Element("div", {className: "genericTasksRequirementsActionsContainer"});
        var genericTasksRewardsActionsContainer = new Element("div", {className: "genericTasksRewardsActionsContainer"});
        	
        var genericTasksRequirementsAddItem = new Element("a", {className: "genericTasksRequirementsAddItem", onclick: "javascript:addRequirementItem(null, " + level + ", null, 0);"}).update('Add item');
        genericTasksRequirementsActionsContainer.appendChild(genericTasksRequirementsAddItem);
        genericTasksRequirementsContainer.appendChild(genericTasksRequirementsActionsContainer);
		    
        var genericTasksRewardsAddItem = new Element("a", {className: "genericTasksRewardsAddItem", onclick: "javascript:addRewardItem(null, " + level + ", null, 0);"}).update('Add item');
        genericTasksRewardsActionsContainer.appendChild(genericTasksRewardsAddItem);
        genericTasksRewardsContainer.appendChild(genericTasksRewardsActionsContainer);

        genericTaskLevel.appendChild(genericTaskLevelId);
        genericTaskLevel.appendChild(genericTaskLevelRequirementItemsCount);
    		genericTaskLevel.appendChild(genericTaskLevelRewardItemsCount);

    		genericTaskLevel.appendChild(genericTaskLevelTitle);
        genericTaskLevel.appendChild(genericTaskLevelContainer);
        genericTaskLevelContainer.appendChild(genericTasksRequirementsTitle);
        genericTaskLevelContainer.appendChild(genericTasksRequirementsContainer);
        genericTaskLevelContainer.appendChild(genericTasksRewardsTitle);
        genericTaskLevelContainer.appendChild(genericTasksRewardsContainer);
        
        $('form').appendChild(genericTaskLevel);
        
        var moneyRequirement = new Element("div", {className: "genericTasksRequirement"});
        var moneyRequirementItem = new Element("div", {className: "genericTasksItem"}).update('Money');
        var moneyRequirementValue = new Element("div", {className: "genericTasksValue"});
        var moneyRequirementValueInput = new Element("input", {type: "text", value: requirementMoney, name: "requirementMoney." + level});
        
        moneyRequirementValue.appendChild(moneyRequirementValueInput);
        moneyRequirement.appendChild(moneyRequirementItem);
        moneyRequirement.appendChild(moneyRequirementValue);
        genericTasksRequirementsContainer.appendChild(moneyRequirement);
        
        var moneyReward = new Element("div", {className: "genericTasksReward"});
        var moneyRewardItem = new Element("div", {className: "genericTasksItem"}).update('Money');
        var moneyRewardValue = new Element("div", {className: "genericTasksValue"});
        var moneyRewardValueInput = new Element("input", {type: "text", value: rewardMoney, name: "rewardMoney." + level});
        
        moneyRewardValue.appendChild(moneyRewardValueInput);
        moneyReward.appendChild(moneyRewardItem);
        moneyReward.appendChild(moneyRewardValue);
        genericTasksRewardsContainer.appendChild(moneyReward);
			}

      function addRewardItem(id, level, itemId, count) {
        var genericTaskLevel = $('genericTaskLevel_' + level);
        var itemCountInput = $$("[name=rewardItemsCount." + level + "]")[0];
        var itemIndex = parseInt(itemCountInput.value);
        
        var genericTasksRewardsContainer = genericTaskLevel.down('.genericTasksRewardsContainer'); 
        var genericTasksReward = new Element("div", {className: "genericTasksReward"});
        var genericTasksItem = new Element("div", {className: "genericTasksItem"});
        var genericTasksItemSelect = new Element("select", {className: "genericTasksItemSelect", name: "rewardItem." + level + "." + itemIndex});
        var genericTasksValue = new Element("div", {className: "genericTasksValue"});
        var genericTasksValueInput = new Element("input", {type: "text", value: count, name: "rewardItemCount." + level + "." + itemIndex});

        var genericTasksRewardItemId = new Element("input", {type: "hidden", value: id, name: "rewardItemId." + level + "." + itemIndex});
            
        ITEMS.each(function (pair) {
          var option = new Element("option", { value: pair.key }).update(pair.value);
          if (pair.key == itemId) {
            option.setAttribute("selected", "selected");
          }
          
          genericTasksItemSelect.appendChild(option);
        });
        
        genericTasksItem.appendChild(genericTasksItemSelect);
        genericTasksValue.appendChild(genericTasksValueInput);
        genericTasksReward.appendChild(genericTasksRewardItemId);
        genericTasksReward.appendChild(genericTasksItem);
        genericTasksReward.appendChild(genericTasksValue);
        genericTasksRewardsContainer.appendChild(genericTasksReward);
        
        itemCountInput.value = itemIndex + 1;
      }
		      
      function addRequirementItem(id, level, itemId, count) {
        var genericTaskLevel = $('genericTaskLevel_' + level);
        var itemCountInput = $$("[name=requirementItemsCount." + level + "]")[0];
        var itemIndex = parseInt(itemCountInput.value);
        
        var genericTasksRequirementsContainer = genericTaskLevel.down('.genericTasksRequirementsContainer'); 
        var genericTasksRequirement = new Element("div", {className: "genericTasksRequirement"});
        var genericTasksItem = new Element("div", {className: "genericTasksItem"});
        var genericTasksItemSelect = new Element("select", {className: "genericTasksItemSelect", name: "requirementItem." + level + "." + itemIndex});
        var genericTasksValue = new Element("div", {className: "genericTasksValue"});
        var genericTasksValueInput = new Element("input", {type: "text", value: count, name: "requirementItemCount." + level + "." + itemIndex});

        var genericTasksRequirementId = new Element("input", {type: "hidden", value: id, name: "requirementItemId." + level + "." + itemIndex});
            
        ITEMS.each(function (pair) {
          var option = new Element("option", { value: pair.key }).update(pair.value);
          if (pair.key == itemId) {
            option.setAttribute("selected", "selected");
          }
          
          genericTasksItemSelect.appendChild(option);
        });
        
        genericTasksItem.appendChild(genericTasksItemSelect);
        genericTasksValue.appendChild(genericTasksValueInput);
        genericTasksRequirement.appendChild(genericTasksRequirementId);
        genericTasksRequirement.appendChild(genericTasksItem);
        genericTasksRequirement.appendChild(genericTasksValue);
        genericTasksRequirementsContainer.appendChild(genericTasksRequirement);
        
        itemCountInput.value = itemIndex + 1;
      }
			
			function addNewLevel() {
			  addLevel(null, NEXT_LEVEL_NUMBER, 0, 0);
	          
			  $('levelCount').value = NEXT_LEVEL_NUMBER;
		    NEXT_LEVEL_NUMBER++;
			}
			
			function save() {
				$('form').submit();
			}
			
			function load(event) {
<%
        for (GeneralTaskLevel generalTaskLevel : generalTaskLevels) {
          TaskRewards taskRewards = taskController.findTaskRewardsById(generalTaskLevel.getTaskRewardsId());
          TaskRequirements taskRequirements = taskController.findTaskRequirementsById(generalTaskLevel.getTaskRequirementsId());
            
          out.append("addLevel(");
          out.append(String.valueOf(generalTaskLevel.getId().getId()));
          out.append(",");
          out.append(String.valueOf(generalTaskLevel.getLevelNumber()));
          out.append(",");
          out.append(String.valueOf(taskRewards.getMoney()));
          out.append(",");
          out.append(String.valueOf(taskRequirements.getMoney()));
          out.append(");");
          
          List<TaskRequirementItem> taskRequirementItems = taskController.listTaskRequirementItems(taskRequirements);
          for (TaskRequirementItem taskRequirementItem : taskRequirementItems) {
            out.append("addRequirementItem(");
            out.append(String.valueOf(taskRequirementItem.getId().getId()));
            out.append(",");
            out.append(String.valueOf(generalTaskLevel.getLevelNumber()));
            out.append(",");
            out.append(String.valueOf(taskRequirementItem.getItemId()));
            out.append(",");
            out.append(String.valueOf(taskRequirementItem.getCount()));
            out.append(");");
          }
          
          List<TaskRewardItem> taskRewardItems = taskController.listTaskRewardItems(taskRewards);
          for (TaskRewardItem taskRewardItem : taskRewardItems) {
            out.append("addRewardItem(");
            out.append(String.valueOf(taskRewardItem.getId().getId()));
            out.append(",");
            out.append(String.valueOf(generalTaskLevel.getLevelNumber()));
            out.append(",");
            out.append(String.valueOf(taskRewardItem.getItemId()));
            out.append(",");
            out.append(String.valueOf(taskRewardItem.getCount()));
            out.append(");");
          }
        }      
%>
			}
		</script>
  </head>
  <body onload="load(event);">
    <form id="form" method="POST">
  
      <input type="hidden" name="levelCount" id="levelCount" value="${levelCount}"/>
    </form>

    <div class="genericTaskLevelActions">
      <a class="genericTaskLevelAction genericTaskLevelAddLevelAction" onclick="javascript:addNewLevel();">Add Level</a>
    </div>

  </body>
</html>